#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <linux/fb.h>
#include <linux/input.h> // for event_input

enum direction {left, right};

enum direction touch_panel(int tp)
{
    struct input_event buf;

    int x1, y1; // 起点坐标
    int x2, y2; // 终点坐标
    bool x1done = false;
    bool y1done = false;

    while(1)
    {
        read(tp, &buf, sizeof(buf));

        if (buf.type == EV_ABS && buf.code == ABS_X)
        {
            // 获取起点坐标
            if(!x1done)
            {
                x1 = buf.value;
                x1done = true;
            }
            // 获取除了起点之外的坐标
            else
                x2 = buf.value;
        }
        if(buf.type == EV_ABS && buf.code == ABS_Y)
        {
            if(!y1done)
            {
                y1 = buf.value;
                y1done = true;
            }
            else
                y2 = buf.value;
        }

        // 手指离开触屏
        if(buf.type == EV_KEY && buf.code == BTN_TOUCH && buf.value == 0)
            break;
    }


    if(x1-x2 > 50 && abs(y2-y1) < 50)
        return left;
    if(x2-x1 > 50 && abs(y2-y1) < 50)
        return right;
}

int main(int argc, char const *argv[])
{
    // 1. 打开触摸屏文件
    int tp = open("/dev/input/event0", O_RDWR);

    while(1)
    {
        enum direction dir = touch_panel(tp);

        if(dir == left)
            printf("向左\n");
        if(dir == right)
            printf("向右\n");
    }

    return 0;
}
